package com.mercadoutils.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.domain.Item;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;

@Controller
public class ListingController {
	@RequestMapping("/listing.html")
	 public String doRedirect(@RequestParam("listing") String listing,
			 @RequestParam(value="titulo",required=false) String title,
			 @RequestParam(value="precio",required=false,defaultValue="0") double price,
			 @RequestParam(value="cantidad",required=false,defaultValue="0") int available_quantity,
			 @RequestParam(value="Category",required=false) String category_id,
			 @RequestParam(value="descripcion",required=false) String description,
			 @RequestParam(value="condicion",required=false) String condition,
			 @RequestParam(value="tipoPublicacion",required=false) String listing_type_id,
			 @RequestParam(value="moneda",required=false) String currency_id,
			 @RequestParam(value="imagen",required=false) String imagen,
			 Model model) throws MeliException, IOException, ServletException, SQLException 
	 {
		HttpSession session = SesionListener.getSession();
        Meli m = (Meli) session.getAttribute("meli");
		String subtitle = "subtitulo por defecto";
		String buying_mode = "buy_it_now";
		String video_id = null;
		String warranty = "12 meses";
		String pictures[] = new String[1];
		pictures[0]="malditacomilla"+imagen;
		
		if(listing.equals("showForm")){
			System.out.println("entro showform");
		 Connection conexion = PoolConectionsSingleton.getConection();
		 Statement st = conexion.createStatement();
	     ResultSet rs;
	     rs = st.executeQuery("select id from currencies where country = (select country from muuser where id = "+session.getAttribute("userId")+") or country = 'Todos'");
	     String monedaRadioButton = "";
	     int i = 0;
	     while(rs.next()){
	    	 if(rs.getString("id").equals("EUR")||rs.getString("id").equals("USD"))
	    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\" disabled>"+rs.getString("id")+"</label>";
	    	 else
	    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\">"+rs.getString("id")+"</label>";
	    	 i++;
	     }
		 model.addAttribute("monedaRadioButton",monedaRadioButton);
		 model.addAttribute("nombre",session.getAttribute("nombre"));
		 model.addAttribute("apellido",session.getAttribute("apellido"));
		 model.addAttribute("role",session.getAttribute("role"));
		 model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
			return "listing";
		}
		if(listing.equals("publish")){
			Item item = new Item(title,subtitle, price,currency_id, available_quantity,
								buying_mode, category_id, description, condition, listing_type_id,
								video_id,warranty,pictures);
			
			 Connection conexion = PoolConectionsSingleton.getConection();
			 Statement st = conexion.createStatement();
		     ResultSet rs;
		     rs = st.executeQuery("select id from currencies where country = (select country from muuser where id = "+session.getAttribute("userId")+") or country = 'Todos'");
		     String monedaRadioButton = "";
		     int i = 0;
		     while(rs.next()){
		    	 if(rs.getString("id").equals("EUR")||rs.getString("id").equals("USD"))
		    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\" disabled>"+rs.getString("id")+"</label>";
		    	 else
		    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\">"+rs.getString("id")+"</label>";
		    	 i++;
		     }
			 
			 
			Gson gson = new Gson();
			String json = gson.toJson(item);
			json = json.replace("malditacomilla", "source\":\"");
			json = json.replace("[", "[{");
			json = json.replace("]", "}]");
			
			FluentStringsMap params = new FluentStringsMap();
	        params.add("access_token", m.getAccessToken());
	        Response r = m.post("/items", params,json);
	        System.out.println(json);
	        System.out.println(r.getResponseBody().toString());
	        model.addAttribute("monedaRadioButton",monedaRadioButton);
		    model.addAttribute("nombre",session.getAttribute("nombre"));
		    model.addAttribute("apellido",session.getAttribute("apellido"));
		    model.addAttribute("role",session.getAttribute("role"));
		    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
			return "listing";
		}
		else{
			
		    model.addAttribute("nombre",session.getAttribute("nombre"));
		    model.addAttribute("apellido",session.getAttribute("apellido"));
		    model.addAttribute("role",session.getAttribute("role"));
		    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
			return "listing";
		}
	 }
	
	@RequestMapping("/listing2.html")
	 public @ResponseBody String doRedirect2(@RequestParam(value="titulo",required=false) String title,
			 @RequestParam(value="precio",required=false,defaultValue="0") double price,
			 @RequestParam(value="cantidad",required=false,defaultValue="0") int available_quantity,
			 @RequestParam(value="Category",required=false) String category_id,
			 @RequestParam(value="descripcion",required=false) String description,
			 @RequestParam(value="condicion",required=false) String condition,
			 @RequestParam(value="tipoPublicacion",required=false) String listing_type_id,
			 @RequestParam(value="moneda",required=false) String currency_id,
			 @RequestParam(value="imagen",required=false) String imagen,
			 Model model) throws MeliException, IOException, ServletException, SQLException 
	 {
		System.out.println("entro publish");
		HttpSession session = SesionListener.getSession();
       Meli m = (Meli) session.getAttribute("meli");
		String subtitle = "subtitulo por defecto";
		String buying_mode = "buy_it_now";
		String video_id = null;
		String warranty = "12 meses";
		String pictures[] = new String[1];
		pictures[0]="malditacomilla"+imagen;

			Item item = new Item(title,subtitle, price,currency_id, available_quantity,
								buying_mode, category_id, description, condition, listing_type_id,
								video_id,warranty,pictures);
			
			 Connection conexion = PoolConectionsSingleton.getConection();
			 Statement st = conexion.createStatement();
		     ResultSet rs;
		     rs = st.executeQuery("select id from currencies where country = (select country from muuser where id = "+session.getAttribute("userId")+") or country = 'Todos'");
		     String monedaRadioButton = "";
		     int i = 0;
		     while(rs.next()){
		    	 if(rs.getString("id").equals("EUR")||rs.getString("id").equals("USD"))
		    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\" disabled>"+rs.getString("id")+"</label>";
		    	 else
		    		 monedaRadioButton+="<label><input class=\"uniform\" type=\"radio\" id=\"moneda"+i+"\" name=\"moneda\" value=\""+rs.getString("id")+"\">"+rs.getString("id")+"</label>";
		    	 i++;
		     }
			 
			 
			Gson gson = new Gson();
			String json = gson.toJson(item);
			json = json.replace("malditacomilla", "source\":\"");
			json = json.replace("[", "[{");
			json = json.replace("]", "}]");
			
			FluentStringsMap params = new FluentStringsMap();
	        params.add("access_token", m.getAccessToken());
	        Response r = m.post("/items", params,json);
	        System.out.println(json);
	        System.out.println(r.getResponseBody().toString());
	        model.addAttribute("monedaRadioButton",monedaRadioButton);
		    model.addAttribute("nombre",session.getAttribute("nombre"));
		    model.addAttribute("apellido",session.getAttribute("apellido"));
		    model.addAttribute("role",session.getAttribute("role"));
		    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		    JsonElement jelement = new JsonParser().parse(r.getResponseBody().toString()); 
			JsonObject jobject = jelement.getAsJsonObject();
			System.out.println(jobject.get("status").toString());
		    if(jobject.get("status").toString().equals("\"not_yet_active\""))
		    	return "Producto publicado correctamente";
		    else
		    	return "Error: "+jobject.getAsJsonArray("cause").get(0).getAsJsonObject().get("message");		
	}
	
	@RequestMapping("/listingAddAttributes.html")
	 public String doRedirect(Model model) throws MeliException, IOException 
	 {
		HttpSession session = SesionListener.getSession();
	    model.addAttribute("nombre",session.getAttribute("nombre"));
	    model.addAttribute("apellido",session.getAttribute("apellido"));
	    model.addAttribute("role",session.getAttribute("role"));
	    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		model.addAttribute("categoria","Seleccione una categoria");
		return "listingAddAttributes";
	 }
	
	
	 public void publicar(@RequestParam("titulo") String titulo){
		 
		 
	 }
}

